package com.zyy.rabbitmq.routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2023/05/22 22:04
 */
public class Producer {

    public static void main(String[] args) {
        //创建连接并设置连接属性
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setVirtualHost("/");
        connectionFactory.setHost("39.108.49.252");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        Connection connection = null;
        Channel channel = null;
        try {
            //从连接工厂中新建连接
            connection = connectionFactory.newConnection("producer-1");
            //从连接中创建通道
            channel = connection.createChannel();
            //声明交换机
            String exchangeName = "fanout.java.exchange";
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT, true);
            //声明队列
            String queueName1 = "queue5";
            String queueName2 = "queue6";
            channel.queueDeclare(queueName1, true, false, false, null);
            channel.queueDeclare(queueName2, true, false, false, null);
            //绑定队列
            channel.queueBind(queueName1, exchangeName, "", null);
            channel.queueBind(queueName2, exchangeName, "", null);
            //发送消息
            String message = "hello fanout.java.exchange";
            channel.basicPublish(exchangeName, "", null, message.getBytes());
            System.out.println("消息发送成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            //关闭通道和连接
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }

            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
